﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.SceneManagement;
using YooAsset;
using Panty;
using Panty.Test;

namespace Panty
{
    public partial interface IResLoader
    {
         void Release();
    }
    public partial class ResLoader
    {
       public virtual  void Release() { }
    }
}

public class YooResLoader : ResLoader
{
    private HashSet<AssetHandle> mHandles;
    private HashSet<ResourcePackage> mPackegs;
    public override bool Preload => true;
    protected override void OnInit()
    {            
        // 初始化资源系统
        YooAssets.Initialize();
        mHandles = new HashSet<AssetHandle>();
        mPackegs = new HashSet<ResourcePackage>();

        //设置15分钟自动回收
        this.GetModel<ITaskScheduler>().AddDelayTask(10 * 60, Release, true);
        base.OnInit();
    }
    /// <summary>
    /// 异步加载
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="packageOrLocation"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public async override Task<T> AsyncLoad<T>(string packageOrLocation)
    {
        string[] split = packageOrLocation.Split(':', '：');
#if UNITY_EDITOR
        if (split.Length != 2) throw new Exception("指令错误");
#endif
        ResourcePackage packegs = YooAssets.GetPackage(split[0]);
        AssetHandle obj = packegs.LoadAssetAsync<T>(split[1]);//加载资源
        mHandles.Add(obj);
        mPackegs.Add(packegs);
        await obj.Task;
        return obj.AssetObject as T;
    }
    /// <summary>
    /// 异步加载，加载完成回调
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="packageOrLocation"></param>
    /// <param name="call"></param>
    /// <exception cref="Exception"></exception>
    public override async void AsyncLoad<T>(string packageOrLocation, Action<T> call)
    {
#if UNITY_EDITOR
        if (call == null) throw new Exception("无意义的回调");
#endif
        call(await AsyncLoad<T>(packageOrLocation));
    }

    /// <summary>
    /// 同步加载
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="packageOrLocation"></param>
    /// <returns></returns>
    /// <exception cref="Exception"></exception>
    public override T SyncLoad<T>(string packageOrLocation)
    {
        string[] split = packageOrLocation.Split(':', '：');
#if UNITY_EDITOR
        if (split.Length != 2) throw new Exception("指令错误");
#endif
        ResourcePackage packegs = YooAssets.GetPackage(split[0]);
        AssetHandle obj = packegs.LoadAssetSync<T>(split[1]);//加载资源
        mHandles.Add(obj);
        mPackegs.Add(packegs);
        Debug.Log(obj.AssetObject.GetType());
        return obj.AssetObject as T;
    }


    /// <summary>
    /// 场景切换释放资源
    /// </summary>
    /// <param name="scene"></param>
    protected override void OnSceneUnloaded(Scene scene)
    {
        foreach (AssetHandle handle in mHandles)
        {
            handle.Release();
        }
        mHandles.Clear();
        foreach (ResourcePackage packegs in mPackegs)
        {
            packegs.UnloadUnusedAssetsAsync();
        }
        mPackegs.Clear();
        base.OnSceneUnloaded(scene);
        Debug.Log("资源被清理");
    }



    /// <summary>
    /// 手动清理资源
    /// </summary>
    public override void Release()
    {
        foreach (AssetHandle handle in mHandles)
        {
            handle.Release();
        }
        mHandles.Clear();
        foreach (ResourcePackage packegs in mPackegs)
        {
            packegs.UnloadUnusedAssetsAsync();
            //packegs.UnloadAllAssetsAsync();
        }
        mPackegs.Clear();
        System.GC.Collect();
        Debug.Log("自动清理10分钟清理资源，自动回收");
    }
}